import Vue from 'vue'
import Vuex from 'vuex'

// 1.安装插件
Vue.use(Vuex);

// 2.创建Store对象
const store = new Vuex.Store({
  state: {
    cartList: []
  },
  // mutations唯一的目的就是修改state中的状态
  // mutations中的每一个方法尽可能比较单一
  mutations: {
    addCounter(state, payload) {
      payload.count++;
    },
    addCart(state, payload) {
      payload.checked = true;
      payload.count = 1;
      state.cartList.push(payload);
    }
  },
  actions: {
    addToCart(context, payload) {
      let oldProduct = null;
      for (let item of context.state.cartList) {
        if (item.iid === payload.iid) {
          oldProduct = item;
        }
      }
      if (oldProduct) {
        // oldProduct.count += 1
        context.commit('addCounter', oldProduct)
      } else {
        context.commit('addCart', payload)
      }
    },
  }
})

// 3.挂载到Vue实例上
export default store;
